/*! 
 * \file test_parser_adapter_comprehensive.cpp
 * \project WonderTrader
 *
 * \author Generated
 * \date 2024/03/20
 * 
 * \brief ParserAdapter综合测试文件
 * 
 * \details 测试ParserAdapter类的全面功能，包括：
 *          - 行情解析器适配器基础功能测试
 *          - 数据订阅和分发机制测试
 *          - 多种数据类型处理测试（Tick、K线、Level2等）
 *          - 连接状态管理测试
 *          - 错误处理和异常恢复测试
 *          - 性能特性测试
 *          - 多线程安全性测试
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <thread>
#include <vector>
#include <chrono>
#include <atomic>
#include <memory>

// 包含必要的头文件
#include "../../src/WtCore/ParserAdapter.h"
#include "../../src/Includes/WTSDataDef.hpp"
#include "../../src/Includes/WTSVariant.hpp"
#include "../../src/Includes/IParserApi.h"

using namespace wtp;
using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;
using ::testing::InSequence;

/**
 * @class MockParserApi
 * @brief 模拟行情解析器API类
 * 
 * @details 用于测试ParserAdapter的模拟行情解析器API
 */
class MockParserApi : public IParserApi {
public:
    MOCK_METHOD(bool, init, (WTSVariant* config), (override));
    MOCK_METHOD(void, release, (), (override));
    MOCK_METHOD(bool, connect, (), (override));
    MOCK_METHOD(bool, disconnect, (), (override));
    MOCK_METHOD(bool, isConnected, (), (override));
    MOCK_METHOD(void, subscribe, (const CodeSet& vecSymbols), (override));
    MOCK_METHOD(void, unsubscribe, (const CodeSet& vecSymbols), (override));
    MOCK_METHOD(void, registerSpi, (IParserSpi* listener), (override));
};

/**
 * @class MockDataSink
 * @brief 模拟数据接收器类
 * 
 * @details 用于测试ParserAdapter数据分发功能的模拟数据接收器
 */
class MockDataSink : public IDataSink {
public:
    MOCK_METHOD(void, handle_tick, (const char* stdCode, WTSTickData* curTick), (override));
    MOCK_METHOD(void, handle_bar_close, (const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar), (override));
    MOCK_METHOD(void, handle_order_queue, (const char* stdCode, WTSOrdQueData* curOrdQue), (override));
    MOCK_METHOD(void, handle_order_detail, (const char* stdCode, WTSOrdDtlData* curOrdDetail), (override));
    MOCK_METHOD(void, handle_transaction, (const char* stdCode, WTSTransData* curTrans), (override));
    MOCK_METHOD(void, handle_parser_log, (WTSLogLevel ll, const char* message), (override));
};

/**
 * @class ParserAdapterComprehensiveTest
 * @brief ParserAdapter综合测试类
 * 
 * @details 提供ParserAdapter的全面测试环境和测试用例
 */
class ParserAdapterComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 创建模拟对象
        mock_api_ = std::make_shared<MockParserApi>();
        mock_sink_ = std::make_shared<MockDataSink>();
        
        // 创建测试配置
        config_ = WTSVariant::createObject();
        config_->append("host", "127.0.0.1", false);
        config_->append("port", 9999, false);
        config_->append("user", "test_user", false);
        config_->append("pass", "test_pass", false);
        
        // 创建被测试对象
        adapter_ = std::make_unique<ParserAdapter>();
        
        // 设置默认期望
        setupDefaultExpectations();
    }
    
    void TearDown() override {
        config_->release();
        adapter_.reset();
        mock_sink_.reset();
        mock_api_.reset();
    }
    
    /**
     * @brief 设置默认期望
     * @details 为模拟对象设置常用的默认期望行为
     */
    void setupDefaultExpectations() {
        ON_CALL(*mock_api_, isConnected())
            .WillByDefault(Return(true));
        ON_CALL(*mock_api_, init(_))
            .WillByDefault(Return(true));
        ON_CALL(*mock_api_, connect())
            .WillByDefault(Return(true));
        ON_CALL(*mock_api_, disconnect())
            .WillByDefault(Return(true));
    }
    
    /**
     * @brief 创建测试用Tick数据
     * @param code 合约代码
     * @return WTSTickData指针
     */
    WTSTickData* createTestTick(const char* code) {
        WTSTickData* tick = WTSTickData::create(code);
        tick->set_price(100.5);
        tick->set_volume(1000);
        tick->set_turnover(100500.0);
        tick->set_open_interest(5000);
        tick->set_trading_date(20240320);
        tick->set_action_date(20240320);
        tick->set_action_time(93000000);
        return tick;
    }
    
    /**
     * @brief 创建测试用K线数据
     * @param code 合约代码
     * @return WTSBarStruct指针
     */
    WTSBarStruct* createTestBar(const char* code) {
        WTSBarStruct* bar = new WTSBarStruct();
        strcpy(bar->code, code);
        bar->date = 20240320;
        bar->time = 93000;
        bar->open = 100.0;
        bar->high = 101.0;
        bar->low = 99.5;
        bar->close = 100.5;
        bar->vol = 10000;
        bar->money = 1005000.0;
        bar->hold = 5000;
        return bar;
    }

protected:
    std::shared_ptr<MockParserApi> mock_api_;
    std::shared_ptr<MockDataSink> mock_sink_;
    std::unique_ptr<ParserAdapter> adapter_;
    WTSVariant* config_;
};

/**
 * @brief 测试ParserAdapter基础构造和析构
 * @details 验证ParserAdapter对象的正确创建和销毁
 */
TEST_F(ParserAdapterComprehensiveTest, TestBasicConstruction) {
    EXPECT_NE(adapter_, nullptr);
    EXPECT_STREQ(adapter_->id(), "");  // 默认ID为空
}

/**
 * @brief 测试ParserAdapter初始化功能
 * @details 验证ParserAdapter的初始化过程和配置加载
 */
TEST_F(ParserAdapterComprehensiveTest, TestInitialization) {
    // 设置期望
    EXPECT_CALL(*mock_api_, init(_))
        .Times(1)
        .WillOnce(Return(true));
    
    // 执行测试
    bool result = adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    
    // 验证结果
    EXPECT_TRUE(result);
    EXPECT_STREQ(adapter_->id(), "test_parser");
}

/**
 * @brief 测试ParserAdapter连接功能
 * @details 验证ParserAdapter的连接建立和状态管理
 */
TEST_F(ParserAdapterComprehensiveTest, TestConnection) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    
    // 设置期望
    EXPECT_CALL(*mock_api_, connect())
        .Times(1)
        .WillOnce(Return(true));
    EXPECT_CALL(*mock_api_, isConnected())
        .Times(AtLeast(1))
        .WillRepeatedly(Return(true));
    
    // 执行测试
    bool result = adapter_->run();
    
    // 验证结果
    EXPECT_TRUE(result);
    EXPECT_TRUE(adapter_->isConnected());
}

/**
 * @brief 测试ParserAdapter断开连接功能
 * @details 验证ParserAdapter的连接断开和清理
 */
TEST_F(ParserAdapterComprehensiveTest, TestDisconnection) {
    // 初始化并连接
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->run();
    
    // 设置期望
    EXPECT_CALL(*mock_api_, disconnect())
        .Times(1)
        .WillOnce(Return(true));
    
    // 执行测试
    adapter_->release();
    
    // 验证结果通过期望验证
}

/**
 * @brief 测试数据订阅功能
 * @details 验证ParserAdapter的数据订阅机制
 */
TEST_F(ParserAdapterComprehensiveTest, TestDataSubscription) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->run();
    
    // 准备订阅数据
    CodeSet codes;
    codes.insert("SHFE.rb2405");
    codes.insert("SHFE.hc2405");
    
    // 设置期望
    EXPECT_CALL(*mock_api_, subscribe(_))
        .Times(1);
    
    // 执行测试
    adapter_->subscribe(codes);
    
    // 验证结果通过期望验证
}

/**
 * @brief 测试数据取消订阅功能
 * @details 验证ParserAdapter的数据取消订阅机制
 */
TEST_F(ParserAdapterComprehensiveTest, TestDataUnsubscription) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->run();
    
    // 准备取消订阅数据
    CodeSet codes;
    codes.insert("SHFE.rb2405");
    
    // 设置期望
    EXPECT_CALL(*mock_api_, unsubscribe(_))
        .Times(1);
    
    // 执行测试
    adapter_->unsubscribe(codes);
    
    // 验证结果通过期望验证
}

/**
 * @brief 测试Tick数据处理
 * @details 验证ParserAdapter对Tick数据的接收和分发
 */
TEST_F(ParserAdapterComprehensiveTest, TestTickDataHandling) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->addSink(mock_sink_.get());
    
    // 创建测试数据
    WTSTickData* tick = createTestTick("SHFE.rb2405");
    
    // 设置期望
    EXPECT_CALL(*mock_sink_, handle_tick(_, _))
        .Times(1);
    
    // 执行测试
    adapter_->handleTick("SHFE.rb2405", tick);
    
    // 清理
    tick->release();
}

/**
 * @brief 测试K线数据处理
 * @details 验证ParserAdapter对K线数据的接收和分发
 */
TEST_F(ParserAdapterComprehensiveTest, TestBarDataHandling) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->addSink(mock_sink_.get());
    
    // 创建测试数据
    WTSBarStruct* bar = createTestBar("SHFE.rb2405");
    
    // 设置期望
    EXPECT_CALL(*mock_sink_, handle_bar_close(_, _, _, _))
        .Times(1);
    
    // 执行测试
    adapter_->handleBar("SHFE.rb2405", "m1", 1, bar);
    
    // 清理
    delete bar;
}

/**
 * @brief 测试多数据接收器管理
 * @details 验证ParserAdapter对多个数据接收器的管理
 */
TEST_F(ParserAdapterComprehensiveTest, TestMultipleSinkManagement) {
    // 创建多个模拟接收器
    auto sink1 = std::make_shared<MockDataSink>();
    auto sink2 = std::make_shared<MockDataSink>();
    
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->addSink(sink1.get());
    adapter_->addSink(sink2.get());
    
    // 创建测试数据
    WTSTickData* tick = createTestTick("SHFE.rb2405");
    
    // 设置期望 - 两个接收器都应该收到数据
    EXPECT_CALL(*sink1, handle_tick(_, _))
        .Times(1);
    EXPECT_CALL(*sink2, handle_tick(_, _))
        .Times(1);
    
    // 执行测试
    adapter_->handleTick("SHFE.rb2405", tick);
    
    // 清理
    tick->release();
}

/**
 * @brief 测试错误处理机制
 * @details 验证ParserAdapter的错误处理和异常恢复能力
 */
TEST_F(ParserAdapterComprehensiveTest, TestErrorHandling) {
    // 设置API初始化失败的期望
    EXPECT_CALL(*mock_api_, init(_))
        .Times(1)
        .WillOnce(Return(false));
    
    // 执行测试
    bool result = adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    
    // 验证结果
    EXPECT_FALSE(result);
}

/**
 * @brief 测试连接失败处理
 * @details 验证ParserAdapter对连接失败的处理
 */
TEST_F(ParserAdapterComprehensiveTest, TestConnectionFailure) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    
    // 设置连接失败的期望
    EXPECT_CALL(*mock_api_, connect())
        .Times(1)
        .WillOnce(Return(false));
    
    // 执行测试
    bool result = adapter_->run();
    
    // 验证结果
    EXPECT_FALSE(result);
}

/**
 * @brief 测试日志处理功能
 * @details 验证ParserAdapter的日志记录和分发功能
 */
TEST_F(ParserAdapterComprehensiveTest, TestLogHandling) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->addSink(mock_sink_.get());
    
    // 设置期望
    EXPECT_CALL(*mock_sink_, handle_parser_log(_, _))
        .Times(1);
    
    // 执行测试
    adapter_->handleParserLog(LL_INFO, "Test log message");
}

/**
 * @brief 测试性能特性
 * @details 验证ParserAdapter的性能表现
 */
TEST_F(ParserAdapterComprehensiveTest, TestPerformanceCharacteristics) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->addSink(mock_sink_.get());
    
    const int test_count = 10000;
    
    // 设置期望
    EXPECT_CALL(*mock_sink_, handle_tick(_, _))
        .Times(test_count);
    
    // 性能测试
    auto start = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < test_count; ++i) {
        WTSTickData* tick = createTestTick("SHFE.rb2405");
        adapter_->handleTick("SHFE.rb2405", tick);
        tick->release();
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    std::cout << "处理 " << test_count << " 个Tick数据耗时: " 
              << duration.count() << " 微秒" << std::endl;
    
    // 验证性能要求（每个Tick处理时间应小于100微秒）
    EXPECT_LT(duration.count() / test_count, 100);
}

/**
 * @brief 测试多线程安全性
 * @details 验证ParserAdapter在多线程环境下的安全性
 */
TEST_F(ParserAdapterComprehensiveTest, TestThreadSafety) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    adapter_->addSink(mock_sink_.get());
    
    const int thread_count = 4;
    const int operations_per_thread = 1000;
    std::atomic<int> success_count{0};
    
    // 设置期望
    EXPECT_CALL(*mock_sink_, handle_tick(_, _))
        .Times(thread_count * operations_per_thread);
    
    // 创建多个线程同时处理数据
    std::vector<std::thread> threads;
    for (int i = 0; i < thread_count; ++i) {
        threads.emplace_back([&, i]() {
            for (int j = 0; j < operations_per_thread; ++j) {
                try {
                    WTSTickData* tick = createTestTick("SHFE.rb2405");
                    adapter_->handleTick("SHFE.rb2405", tick);
                    tick->release();
                    success_count++;
                } catch (...) {
                    // 捕获异常但不处理，用于测试线程安全性
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证结果
    EXPECT_EQ(success_count.load(), thread_count * operations_per_thread);
    std::cout << "多线程测试成功操作数: " << success_count.load() 
              << "/" << (thread_count * operations_per_thread) << std::endl;
}

/**
 * @brief 测试边界条件处理
 * @details 验证ParserAdapter对各种边界条件的处理
 */
TEST_F(ParserAdapterComprehensiveTest, TestBoundaryConditions) {
    // 初始化适配器
    adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    
    // 测试空指针处理
    EXPECT_NO_THROW(adapter_->handleTick("", nullptr));
    EXPECT_NO_THROW(adapter_->handleBar("", "", 0, nullptr));
    
    // 测试空字符串处理
    WTSTickData* tick = createTestTick("");
    EXPECT_NO_THROW(adapter_->handleTick("", tick));
    tick->release();
    
    // 测试极大数值处理
    tick = createTestTick("SHFE.rb2405");
    tick->set_price(DBL_MAX);
    tick->set_volume(UINT64_MAX);
    EXPECT_NO_THROW(adapter_->handleTick("SHFE.rb2405", tick));
    tick->release();
}

/**
 * @brief 测试完整工作流程
 * @details 验证ParserAdapter的完整工作流程
 */
TEST_F(ParserAdapterComprehensiveTest, TestCompleteWorkflow) {
    InSequence seq;
    
    // 设置完整流程的期望
    EXPECT_CALL(*mock_api_, init(_))
        .Times(1)
        .WillOnce(Return(true));
    EXPECT_CALL(*mock_api_, connect())
        .Times(1)
        .WillOnce(Return(true));
    EXPECT_CALL(*mock_api_, subscribe(_))
        .Times(1);
    EXPECT_CALL(*mock_sink_, handle_tick(_, _))
        .Times(1);
    EXPECT_CALL(*mock_api_, unsubscribe(_))
        .Times(1);
    EXPECT_CALL(*mock_api_, disconnect())
        .Times(1)
        .WillOnce(Return(true));
    
    // 执行完整工作流程
    // 1. 初始化
    bool init_result = adapter_->init("test_parser", "test_parser", config_, mock_api_.get());
    EXPECT_TRUE(init_result);
    
    // 2. 连接
    bool connect_result = adapter_->run();
    EXPECT_TRUE(connect_result);
    
    // 3. 添加数据接收器
    adapter_->addSink(mock_sink_.get());
    
    // 4. 订阅数据
    CodeSet codes;
    codes.insert("SHFE.rb2405");
    adapter_->subscribe(codes);
    
    // 5. 处理数据
    WTSTickData* tick = createTestTick("SHFE.rb2405");
    adapter_->handleTick("SHFE.rb2405", tick);
    tick->release();
    
    // 6. 取消订阅
    adapter_->unsubscribe(codes);
    
    // 7. 断开连接
    adapter_->release();
    
    std::cout << "ParserAdapter完整工作流程测试通过" << std::endl;
} 